package com.qiantu.phone.ui.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.view.SwitchButton;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.LinkageListBean;
import com.qiantu.api.entity.LinkageNewBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshLinkageEvent;
import com.qiantu.phone.ui.adapter.LinkageAdapter;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.widget.StatusLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
public class RoomLinkageActivity extends AppActivity {

    private StatusLayout mStatusLayout;
    private ImageView iv_status_icon;
    private TextView tv_status_text;
    private TextView btn;
    private RecyclerView linkageRecyclerView;
    private LinearLayout ll_Noequipment;
    private int pageIndex = 1;
    private int pageSize = Integer.MAX_VALUE;
    //0全部、1时间变化、2环境变化、4设备变化
    private int linkageType = 0;
    //0、全屋 1、楼层 2、房间
    private int dataType = 0;
    //可能是全屋 可能是楼层 可能是房间
    private String serialNo;
    private LinkageAdapter mLinkageAdapter;
    private List<LinkageListBean> allLinkages;
    private List<LinkageListBean> showlinkages;

    @Log
    public static void start(Context context, String serialNo,int dataType) {
        Intent intent = new Intent(context, RoomLinkageActivity.class);
        intent.putExtra("dataType",dataType);
        intent.putExtra("serialNo", serialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.room_linkage_activity;
    }

    @Override
    protected void initView() {
        serialNo = getIntent().getStringExtra("serialNo");
        dataType = getIntent().getIntExtra("dataType",0);
        EventBus.getDefault().register(this);
        mStatusLayout = findViewById(R.id.status_layout);
//        mStatusLayout.setBackgroundResource(R.drawable.top_round_16dp_secondary_color3);
        linkageRecyclerView = findViewById(R.id.linkage_recycler_view);
        iv_status_icon = findViewById(R.id.iv_status_icon);
        tv_status_text = findViewById(R.id.tv_status_text);
        btn = findViewById(R.id.btn);
        ll_Noequipment = findViewById(R.id.ll_Noequipment);
        initRecyclerView();
    }

    private void initRecyclerView() {
        linkageRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mLinkageAdapter = new LinkageAdapter(getContext());
        linkageRecyclerView.setAdapter(mLinkageAdapter);
        mLinkageAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                LinkageListBean linkage = mLinkageAdapter.getItem(position);
                getLinkageSingleData(linkage);
            }
        });
        mLinkageAdapter.setOnChildClickListener(R.id.btn_switch, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                LinkageListBean linkageBean = mLinkageAdapter.getData().get(position);
                setLinkageDisable(linkageBean, !((SwitchButton) childView).isChecked());
            }
        });
    }

    private void getLinkageSingleData(LinkageListBean linkageListBean){
        if(linkageListBean.getVersion() != 1){
            LLHttpManager.getLinkageNew((LifecycleOwner) getContext(), linkageListBean.getLinkageSerialNo(), new HttpCallback<HttpData<LinkageNewBean>>(null) {
                @Override
                public void onStart(Call call) {
                }

                @Override
                public void onSucceed(HttpData<LinkageNewBean> result) {
                    LinkageDataHolder.setLinkageDataNew(result.getData());
                    Intent intent = new Intent(getContext(), EditLinkageActivityNew.class);
                    startActivity(intent);
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }else{
            LLHttpManager.getLinkage((LifecycleOwner) getContext(), linkageListBean.getLinkageSerialNo(), new HttpCallback<HttpData<LinkageBean>>(null) {
                @Override
                public void onStart(Call call) {
                }

                @Override
                public void onSucceed(HttpData<LinkageBean> result) {
                    List<ControllerBean> beans = LLControllerDBManager.getInstance(getContext()).getControllersByProductModel("0x1501");
                    if(beans.size() == 0 || LLSceneLinkageUtil.compareVersion("1.5.0", beans.get(0).getVersion())){
                        convertOldLinkage(result.getData());
                    }else{
                        LinkageDataHolder.setLinkageData(result.getData());
                        Intent intent = new Intent(getContext(), EditLinkageActivity.class);
                        startActivity(intent);
                    }

                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }

    }


    private void setLinkageDisable(LinkageListBean linkageBean, boolean isDisable) {
        LLHttpManager.setLinkageDisable(this, linkageBean.getLinkageSerialNo(), isDisable, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                linkageBean.setDisable(isDisable);
                toast(R.string.set_success);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    @Override
    public void onClick(View view) {
        getLinikageData();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initData() {
        getLinikageData();
    }

    private void getLinikageData() {
        //获取全部联动
        LLHttpManager.getLinkagesNew(this, pageIndex, pageSize, AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo(), new HttpCallback<HttpData<List<LinkageListBean>>>(this) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<List<LinkageListBean>> result) {
                allLinkages = result.getData();
                rebuildData();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    //当前变化无设备
    private void No_equipment() {
        linkageRecyclerView.setVisibility(View.GONE);
        ll_Noequipment.setVisibility(View.VISIBLE);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoAddView();
            }
        });
    }

    //当前变化有设备
    private void Ye_sequipment() {
        linkageRecyclerView.setVisibility(View.VISIBLE);
        ll_Noequipment.setVisibility(View.GONE);
    }

    public void rebuildData(){
        if (this.dataType == 0) {//全屋
            showlinkages = allLinkages;
        }else{
            List<String> roomSerialNos = new ArrayList<>();

            if (this.dataType == 1)//楼层
            {
                List<RoomBean> rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(this.serialNo);
                for (RoomBean room : rooms) {
                    roomSerialNos.add(room.getRoomSerialNo());
                }


            } else if (this.dataType == 2) {//房间
                roomSerialNos.add(this.serialNo);
            }


            showlinkages = new ArrayList<>();
            for(LinkageListBean linkageBean : allLinkages){
                if(roomSerialNos.contains(linkageBean.getRoomSerialNo())){
                    showlinkages.add(linkageBean);
                }
            }
        }

        if (showlinkages == null ||showlinkages.size() == 0) {
            No_equipment();
        }else {
            Ye_sequipment();
            mLinkageAdapter.setData(showlinkages);
        }
    }



    private void gotoAddView(){
//        List<ControllerBean> beans = LLControllerDBManager.getInstance(getContext()).getControllersByProductModel("0x1501");
        if (this.dataType == 0) {//全屋
            LinkageBean addLinkage = new LinkageBean();
            addLinkage.setLinkType(2);
            addLinkage.setRoomSerialNo(RoomBean.ROOM_COMMON_SERIALNO);
            LinkageDataHolder.setLinkageData(addLinkage);
        }else if (this.dataType == 1){//楼层

        } else if (this.dataType == 2) {//房间
            LinkageBean addLinkage = new LinkageBean();
            addLinkage.setLinkType(1);
            addLinkage.setRoomSerialNo(this.serialNo);
            LinkageDataHolder.setLinkageData(addLinkage);
        }
//        if(beans.size() == 0 || LLSceneLinkageUtil.compareVersion("1.4.0", beans.get(0).getVersion())){
//            startActivity(EditLinkageActivityNew.class);
//        }else{
            startActivity(EditLinkageActivity.class);
//        }
    }

    private void convertOldLinkage(LinkageBean oldLinkageBean){
        LinkageNewBean newBean = new LinkageNewBean();
        newBean.setLinkageSerialNo(oldLinkageBean.getLinkageSerialNo());
        newBean.setBid(0);
        newBean.setName(oldLinkageBean.getName());
        newBean.setDecideType(3);
        newBean.setHouseSerialNo(oldLinkageBean.getHouseSerialNo());
        newBean.setRoomSerialNo(oldLinkageBean.getRoomSerialNo());
        newBean.setLinkType(oldLinkageBean.getLinkType());
        newBean.setLinkageTasks(oldLinkageBean.getLinkageTasks());
        newBean.setConditionTimeList(new ArrayList<>());
        newBean.setConditionEnvWeatherList(new ArrayList<>());
        newBean.setConditionEnvTemperatureList(new ArrayList<>());
        newBean.setConditionEnvHumidityList(new ArrayList<>());
        newBean.setConditionEnvAirList(new ArrayList<>());
        newBean.setConditionEnvSunList(new ArrayList<>());
        newBean.setConditionDeviceStateList(new ArrayList<>());
        for(int i = 0;i < oldLinkageBean.getLinkageConditions().size();i++){
            LinkageBean.LinkageCondition oldCondition = oldLinkageBean.getLinkageConditions().get(i);
            switch (oldCondition.getConditionType()){
                case 1:
                    newBean.getConditionTimeList().add(timeConditionConver(oldCondition));
                    break;
                case 4:
                    newBean.getConditionEnvWeatherList().add(weatherConditionConver(oldCondition));
                    break;
                case 6:
                    newBean.getConditionEnvSunList().add(sunConditionConver(oldCondition));
                    break;
                default:
                    newBean.getConditionDeviceStateList().add(deviceConditionConver(oldCondition));
                    break;
            }
        }

        LinkageDataHolder.setLinkageDataNew(newBean);
        Intent intent = new Intent(getContext(), EditLinkageActivityNew.class);
        startActivity(intent);
    }

    private LinkageNewBean.LinkageTimeCondition timeConditionConver(LinkageBean.LinkageCondition oldCondition){
        LinkageNewBean.LinkageTimeCondition timeCondition = new LinkageNewBean.LinkageTimeCondition();
        timeCondition.setRepeatTypeId(oldCondition.getTimingType() == 1 ? 5 : 1);
        timeCondition.setConditionTypeId(1);
        timeCondition.setIcon(oldCondition.getImageUrl());
        timeCondition.setFromHour(oldCondition.getHour());
        timeCondition.setFromMinute(oldCondition.getMinute());
        timeCondition.setToHour(oldCondition.getToHour());
        timeCondition.setToMinute(oldCondition.getToMinute());
        timeCondition.setRepeatFromTime("");
        timeCondition.setRepeatToTime("");
        List<Integer> repeatWeekDays = new ArrayList<>();
        if(oldCondition.isSunday()){
            repeatWeekDays.add(0);
        }
        if(oldCondition.isMonday()){
            repeatWeekDays.add(1);
        }
        if(oldCondition.isTuesday()){
            repeatWeekDays.add(2);
        }
        if(oldCondition.isWednesday()){
            repeatWeekDays.add(3);
        }
        if(oldCondition.isThursday()){
            repeatWeekDays.add(4);
        }
        if(oldCondition.isFriday()){
            repeatWeekDays.add(5);
        }
        if(oldCondition.isSaturday()){
            repeatWeekDays.add(6);
        }
        timeCondition.setRepeatWeekDays(repeatWeekDays);
        timeCondition.setActionTypeId(2);
        timeCondition.setOperatorTypeId(1);
        timeCondition.setSort(oldCondition.getSort());
        return timeCondition;
    }

    private LinkageNewBean.LinkageWeatherCondition weatherConditionConver(LinkageBean.LinkageCondition oldCondition){
        LinkageNewBean.LinkageWeatherCondition weatherCondition = new LinkageNewBean.LinkageWeatherCondition();
        weatherCondition.setConditionTypeId(4);
        weatherCondition.setIcon(oldCondition.getImageUrl());
        weatherCondition.setWeatherKeyValue(oldCondition.getWeatherKeyValue());
        weatherCondition.setAreaTypeId(oldCondition.getAreaType());
        weatherCondition.setAreaName(oldCondition.getAreaName());
        weatherCondition.setAreaCode(oldCondition.getAreaCoding());
        weatherCondition.setLongitude(oldCondition.getLongitude());
        weatherCondition.setLatitude(oldCondition.getLatitude());
        weatherCondition.setActionTypeId(2);
        weatherCondition.setOperatorTypeId(1);
        weatherCondition.setSort(oldCondition.getSort());
        return weatherCondition;
    }

    private LinkageNewBean.LinkageSunCondition sunConditionConver(LinkageBean.LinkageCondition oldCondition){
        LinkageNewBean.LinkageSunCondition sunCondition = new LinkageNewBean.LinkageSunCondition();
        sunCondition.setRepeatTypeId(oldCondition.getTimingType() == 1 ? 5 : 1);
        sunCondition.setConditionTypeId(6);
        sunCondition.setIcon(oldCondition.getImageUrl());
        sunCondition.setDirectionFromTypeId(oldCondition.getSunPositionType());
        sunCondition.setTowardFromTypeId(oldCondition.getTimeLong() > 0 ? 2 : 1);
        sunCondition.setTowardFromMinute(Math.abs(oldCondition.getTimeLong()/60000));//新联动需要时间，旧联动为毫秒，转换 60 * 1000
        sunCondition.setDirectionToTypeId(2);
        sunCondition.setTowardToTypeId(1);
        sunCondition.setTowardToMinute(0);
        sunCondition.setRepeatFromTime("");
        sunCondition.setRepeatToTime("");
        List<Integer> repeatWeekDays = new ArrayList<>();
        if(oldCondition.isSunday()){
            repeatWeekDays.add(0);
        }
        if(oldCondition.isMonday()){
            repeatWeekDays.add(1);
        }
        if(oldCondition.isTuesday()){
            repeatWeekDays.add(2);
        }
        if(oldCondition.isWednesday()){
            repeatWeekDays.add(3);
        }
        if(oldCondition.isThursday()){
            repeatWeekDays.add(4);
        }
        if(oldCondition.isFriday()){
            repeatWeekDays.add(5);
        }
        if(oldCondition.isSaturday()){
            repeatWeekDays.add(6);
        }
        sunCondition.setRepeatWeekDays(repeatWeekDays);
        sunCondition.setActionTypeId(2);
        sunCondition.setOperatorTypeId(1);
        sunCondition.setSort(oldCondition.getSort());
        return sunCondition;
    }

    private LinkageNewBean.LinkageDeviceCondition deviceConditionConver(LinkageBean.LinkageCondition oldCondition){
        LinkageNewBean.LinkageDeviceCondition deviceCondition = new LinkageNewBean.LinkageDeviceCondition();
        deviceCondition.setConditionTypeId(oldCondition.getConditionType());
        deviceCondition.setDeviceSerialNo(oldCondition.getDeviceSerialNo());
        deviceCondition.setDescription(oldCondition.getBriefing());
        deviceCondition.setStateName(oldCondition.getStateName());
        if(oldCondition.getConditionTypeId() == 2  || oldCondition.getConditionTypeId() == 3  || oldCondition.getConditionTypeId() == 12  || oldCondition.getConditionTypeId() == 13 || oldCondition.getConditionTypeId() == 14){
            deviceCondition.setBeginValue(oldCondition.getBeginValue());
        }else{
            if(oldCondition.getStateValue() == null){
                deviceCondition.setBeginValue(0);
            }else{
                deviceCondition.setBeginValue(Integer.parseInt(oldCondition.getStateValue()));
            }
        }
        deviceCondition.setEndValue(oldCondition.getEndValue());
        deviceCondition.setAreaTypeId(oldCondition.getAreaType());
        deviceCondition.setAreaName(oldCondition.getAreaName());
        deviceCondition.setAreaCode(oldCondition.getAreaCoding());
        deviceCondition.setLongitude(oldCondition.getLongitude());
        deviceCondition.setLatitude(oldCondition.getLatitude());
        deviceCondition.setCompareTypeId(oldCondition.getLogicType());
        deviceCondition.setIcon(oldCondition.getBaseImageUrl());
        deviceCondition.setActionTypeId(2);
        deviceCondition.setOperatorTypeId(1);
        deviceCondition.setSort(oldCondition.getSort());
        return deviceCondition;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshLinkageEvent(RefreshLinkageEvent event) {
        initData();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
